import {useNavigate, useParams} from "react-router-dom";
import {useEffect, useState} from "react";
import {Button, Card, Col, Divider, message, Row, Space, Table, Tag, Tree} from "antd";
import Apis from "../../configs/Apis";
import RequestUtils from "../../utils/RequestUtils";
import {
    CaretDownOutlined,
    CaretUpOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    LeftOutlined,
    PlusOutlined,
    RollbackOutlined,
    SaveOutlined
} from "@ant-design/icons";
import BackButton from "../../components/button/BackButton";

const Permission = () => {
    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();
    const {roleId} = useParams();
    const [currentRoleInfo, setCurrentRoleInfo] = useState({
        roleName: "",
        roleDescription: ""
    });
    const [originalPermissions, setOriginalPermissions] = useState([]);
    const [tempPermissions, setTempPermissions] = useState([]);
    const [allPermissions, setAllPermissions] = useState([]);
    const [loading, setLoading] = useState(false);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [allSysPermissions, setAllSysPermissions] = useState({});
    const [saveLoading, setSaveLoading] = useState(false);

    useEffect(() => {
        if (roleId) {
            fetchRolePermissions(roleId);
            fetchAllPermissions();
        }
    }, [roleId]);

    const fetchRolePermissions = (roleId) => {
        setLoading(true);
        RequestUtils.post(Apis.permission.searchRoleById, {id: roleId})
            .then(res => {
                setCurrentRoleInfo({
                    roleName: res.roleName,
                    roleDescription: res.description
                });
                setOriginalPermissions(res.permissions || []);
                setTempPermissions(res.permissions || []);
            })
            .catch(err => {
                messageApi.error("查询角色权限失败: " + err.message);
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const fetchAllPermissions = () => {
        RequestUtils.post(Apis.permission.searchAllPermission, {})
            .then(res => {
                setAllSysPermissions(res);
                // 扁平化权限数据，便于查找
                const flatPermissions = flattenPermissions(res.sonPermissions || []);
                const treeData = convertToTreeData(res.sonPermissions || []);
                setAllPermissions(treeData);
                setExpandedKeys(getExpandedKeys(treeData));
                // 保存扁平化数据用于快速查找
                setAllSysPermissions(prev => ({...prev, flatPermissions}));
            })
            .catch(err => {
                messageApi.error("获取所有权限失败: " + err.message);
            });
    };

    // 扁平化权限数据
    const flattenPermissions = (permissions) => {
        let result = [];
        permissions.forEach(perm => {
            result.push(perm);
            if (perm.sonPermissions) {
                result = [...result, ...flattenPermissions(perm.sonPermissions)];
            }
        });
        return result;
    };

    // 递归转换权限数据为树结构
    const convertToTreeData = (permissions, parentId = 0) => {
        if (!permissions || permissions.length === 0) return [];

        return permissions.map(permission => ({
            title: permission.permissionName,
            key: permission.permissionCode,
            children: convertToTreeData(permission.sonPermissions, permission.permissionCode),
            ...permission
        }));
    };

    // 获取所有可展开的节点
    const getExpandedKeys = (treeData) => {
        const keys = [];
        const traverse = (nodes) => {
            nodes.forEach(node => {
                if (node.children && node.children.length > 0) {
                    keys.push(node.key);
                    traverse(node.children);
                }
            });
        };
        traverse(treeData);
        return keys;
    };

    // 检查权限是否已存在
    const isPermissionExist = (permissionCode) => {
        return tempPermissions.some(p => p.permissionCode === permissionCode);
    };

    // 递归获取所有子权限
    const getAllChildPermissions = (permissionCode, permissions = allSysPermissions.sonPermissions) => {
        if (!permissions) return [];

        const result = [];

        permissions.forEach(perm => {
            if (perm.permissionCode === permissionCode && perm.sonPermissions) {
                // 添加直接子权限
                result.push(...perm.sonPermissions);
                // 递归查找子权限的子权限
                perm.sonPermissions.forEach(child => {
                    result.push(...getAllChildPermissions(child.permissionCode, perm.sonPermissions));
                });
            } else if (perm.sonPermissions) {
                result.push(...getAllChildPermissions(permissionCode, perm.sonPermissions));
            }
        });

        return result;
    };

    // 清理没有子权限的父级权限
    const cleanUpParentPermissions = (currentPermissions) => {
        // 创建权限代码集合便于快速查找
        const permissionCodes = new Set(currentPermissions.map(p => p.permissionCode));

        // 检查父权限是否有子权限存在
        const hasChildrenInList = (parentCode) => {
            const children = getAllChildPermissions(parentCode);
            return children.some(child => permissionCodes.has(child.permissionCode));
        };

        // 过滤掉没有子权限的父权限
        const filtered = currentPermissions.filter(permission => {
            // 如果是叶子节点（没有子权限），保留
            if (getChildCount(permission.permissionCode) === 0) {
                return true;
            }
            // 如果是父节点，检查是否有子权限存在
            return hasChildrenInList(permission.permissionCode);
        });

        // 如果有变化，递归检查是否还需要进一步清理
        if (filtered.length !== currentPermissions.length) {
            return cleanUpParentPermissions(filtered);
        }

        return filtered;
    };

    // 临时添加权限及其所有子权限
    const handleAddPermission = (permissionCode) => {
        // 检查是否已存在
        if (isPermissionExist(permissionCode)) {
            messageApi.warning("该权限已存在");
            return;
        }

        // 从扁平化数据中查找权限
        const permissionToAdd = allSysPermissions.flatPermissions?.find(
            p => p.permissionCode === permissionCode
        );

        if (!permissionToAdd) {
            messageApi.error("找不到该权限信息");
            return;
        }

        // 获取所有子权限
        const childPermissions = getAllChildPermissions(permissionCode);

        // 过滤掉已存在的权限
        const newPermissions = [permissionToAdd, ...childPermissions]
            .filter(p => !isPermissionExist(p.permissionCode));

        if (newPermissions.length === 0) {
            messageApi.warning("所选权限及其子权限均已存在");
            return;
        }

        // 添加新权限
        setTempPermissions(prev => [...prev, ...newPermissions]);
        messageApi.success(`已添加 ${newPermissions.length} 个权限`);
    };

    // 临时移除权限
    const handleRemovePermission = (permissionCode) => {
        // 递归获取所有子权限
        const childPermissions = getAllChildPermissions(permissionCode);
        const permissionsToRemove = [permissionCode, ...childPermissions.map(p => p.permissionCode)];

        // 移除选中的权限及其子权限
        let updatedPermissions = tempPermissions.filter(p => !permissionsToRemove.includes(p.permissionCode));

        // 清理没有子权限的父级权限
        updatedPermissions = cleanUpParentPermissions(updatedPermissions);

        setTempPermissions(updatedPermissions);
        messageApi.success("权限已移除");
    };

    // 处理树节点展开/收起
    const onExpand = (expandedKeys) => {
        setExpandedKeys(expandedKeys);
    };

    // 保存权限变更
    const handleSavePermissions = () => {
        const addedPermissions = tempPermissions.filter(
            temp => !originalPermissions.some(orig => orig.permissionCode === temp.permissionCode)
        );

        const removedPermissions = originalPermissions.filter(
            orig => !tempPermissions.some(temp => temp.permissionCode === orig.permissionCode)
        );

        if (addedPermissions.length === 0 && removedPermissions.length === 0) {
            messageApi.info("没有权限变更需要保存");
            return;
        }

        setSaveLoading(true);
        RequestUtils.post(Apis.permission.assignPermission2Role, {
            roleId: roleId,
            permissionCodes: addedPermissions.map(p => p.permissionCode)
        })
            .then(() => {
                messageApi.success("权限更新成功");
                setOriginalPermissions([...tempPermissions]);
            })
            .catch(err => {
                messageApi.error("保存权限失败: " + err.message);
            })
            .finally(() => {
                setSaveLoading(false);
            });
    };

    // 判断是否有未保存的变更
    const hasUnsavedChanges = () => {
        if (tempPermissions.length !== originalPermissions.length) return true;

        const tempCodes = new Set(tempPermissions.map(p => p.permissionCode));
        const origCodes = new Set(originalPermissions.map(p => p.permissionCode));

        return [...tempCodes].some(code => !origCodes.has(code)) ||
            [...origCodes].some(code => !tempCodes.has(code));
    };

    // 计算子权限数量
    const getChildCount = (permissionCode) => {
        return getAllChildPermissions(permissionCode).length;
    };

    // 撤回所有变更，重新加载数据
    const handleRollbackChanges = () => {
        if (!hasUnsavedChanges()) {
            messageApi.info("没有需要撤回的变更");
            return;
        }

        // 重置临时权限为原始权限
        setTempPermissions([...originalPermissions]);

        // 可选：重新从服务器加载数据
        // fetchRolePermissions(roleId);

        messageApi.success("已撤回所有变更");
    };

    const roleInfoColumns = [
        {
            title: "属性",
            dataIndex: "attribute",
            key: "attribute",
            width: "30%",
            render: text => <span className="text-gray-500">{text}</span>
        },
        {
            title: "详情",
            dataIndex: "value",
            key: "value",
        }
    ];

    const roleInfoData = [
        {
            key: "1",
            attribute: "角色名称",
            value: currentRoleInfo.roleName
        },
        {
            key: "2",
            attribute: "角色描述",
            value: currentRoleInfo.roleDescription
        }
    ];

    const permissionColumns = [
        {
            title: "权限名称",
            dataIndex: "permissionName",
            key: "permissionName",
        },
        {
            title: "权限标识",
            dataIndex: "permissionCode",
            key: "permissionCode",
        },
        {
            title: "子权限数量",
            key: "childCount",
            render: (_, record) => {
                const count = getChildCount(record.permissionCode);
                return count > 0 ? count : '-';
            }
        },
        {
            title: "状态",
            key: "status",
            render: (_, record) => {
                const isOriginal = originalPermissions.some(p => p.permissionCode === record.permissionCode);
                return isOriginal ? (
                    <Tag color="blue">已分配</Tag>
                ) : (
                    <Tag color="orange">待添加</Tag>
                );
            }
        },
        {
            title: "操作",
            key: "action",
            render: (_, record) => {
                const isOriginal = originalPermissions.some(p => p.permissionCode === record.permissionCode);
                return (
                    <Space size="middle">
                        <a onClick={() => handleRemovePermission(record.permissionCode)}>
                            <CloseCircleOutlined style={{color: 'red'}}/> 移除
                        </a>
                        {!isOriginal && (
                            <Tag color="orange" style={{cursor: 'default'}}>
                                未保存
                            </Tag>
                        )}
                    </Space>
                );
            }
        }
    ];

    return (
        <div className="min-h-screen bg-gray-50 p-4 md:p-6">
            {contextHolder}

            <BackButton
                message="返回上一级页面"
                backToLink={-1}
            />

            <Card
                title="当前角色信息"
                className="mb-6 shadow-sm"
                bordered={false}
            >
                <Table
                    dataSource={roleInfoData}
                    columns={roleInfoColumns}
                    pagination={false}
                    size="small"
                    bordered={false}
                />
            </Card>

            <Divider orientation="left" plain>
                <h2 className="text-lg font-semibold">权限分配</h2>
            </Divider>

            <Row gutter={16}>
                <Col span={12}>
                    <Card
                        title={
                            <div className="flex items-center">
                                <CheckCircleOutlined style={{color: 'green', marginRight: 8}}/>
                                已选择的权限
                                {hasUnsavedChanges() ? (
                                        <Tag color="red" style={{marginLeft: 8}}>
                                            有未保存变更
                                        </Tag>
                                    ) :
                                    <Tag color="green" style={{marginLeft: 8}}>
                                        没有产生修改
                                    </Tag>}
                                <Button
                                    style={{marginLeft: '30px'}}
                                    type="primary"
                                    icon={<SaveOutlined/>}
                                    loading={saveLoading}
                                    disabled={!hasUnsavedChanges()}
                                    onClick={handleSavePermissions}
                                >
                                    保存变更
                                </Button>

                                <Button
                                    style={{marginLeft: '15px'}}
                                    type="default"
                                    icon={<RollbackOutlined/>}
                                    disabled={!hasUnsavedChanges()}
                                    onClick={handleRollbackChanges}
                                >
                                    撤回变更
                                </Button>
                            </div>
                        }
                        loading={loading}
                        className="h-full shadow-sm"
                        bordered={false}
                    >
                        {tempPermissions.length > 0 ? (
                            <Table
                                dataSource={tempPermissions}
                                columns={permissionColumns}
                                pagination={false}
                                size="small"
                            />
                        ) : (
                            <div className="text-center py-10 text-gray-500">
                                <p>暂无权限</p>
                            </div>
                        )}
                    </Card>
                </Col>

                <Col span={12}>
                    <Card
                        title={
                            <div className="flex items-center justify-between">
                                <div className="flex items-center">
                                    <PlusOutlined style={{color: 'blue', marginRight: 8}}/>
                                    所有权限
                                </div>
                                <Button
                                    size="small"
                                    onClick={() => setExpandedKeys(getExpandedKeys(allPermissions))}
                                    className="ml-2"
                                >
                                    <CaretDownOutlined/> 展开
                                </Button>
                                <Button
                                    size="small"
                                    onClick={() => setExpandedKeys([])}
                                    className="ml-2"
                                >
                                    <CaretUpOutlined/> 收起
                                </Button>
                            </div>
                        }
                        className="h-full shadow-sm"
                        bordered={false}
                    >
                        <Tree
                            showLine
                            expandedKeys={expandedKeys}
                            treeData={allPermissions}
                            onSelect={(selectedKeys, info) => {
                                handleAddPermission(info.node.key);
                            }}
                            onExpand={onExpand}
                            checkable={false}
                            selectable={true}
                            filterTreeNode={(node) => !isPermissionExist(node.key)}
                            titleRender={(nodeData) => {
                                const isExist = isPermissionExist(nodeData.key);
                                const childCount = getChildCount(nodeData.key);

                                return (
                                    <div className="flex items-center">
                                        {nodeData.title}
                                        {childCount > 0 && (
                                            <Tag color="cyan" style={{marginLeft: 8, fontSize: 12}}>
                                                {childCount}个子权限
                                            </Tag>
                                        )}
                                        {isExist && <Tag color="green" style={{marginLeft: 8}}>已选择</Tag>}
                                    </div>
                                );
                            }}
                        />
                    </Card>
                </Col>
            </Row>
        </div>
    );
};

export default Permission;